package com.ruoyi.inspection.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.inspection.domain.*;
import com.ruoyi.inspection.domain.vo.GovernCheckTaskPlanItemVo;
import com.ruoyi.inspection.mapper.GovernCheckTaskInfoMapper;
import com.ruoyi.inspection.mapper.GovernCheckTaskPlanItemMapper;
import com.ruoyi.inspection.mapper.GovernCheckTaskPlanMapper;
import com.ruoyi.inspection.service.GovernCheckTaskItemService;
import com.ruoyi.inspection.service.GovernCheckTaskPlanItemService;
import com.ruoyi.inspection.service.GovernHiddenInventoryService;
import com.ruoyi.inspection.utils.IdFactory;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 专项任务计划检查项表(GovernCheckTaskPlanItem)表服务实现类
 *
 * @author makejava
 * @since 2024-06-19 16:16:21
 */
@Service("governCheckTaskPlanItemService")
public class GovernCheckTaskPlanItemServiceImpl implements GovernCheckTaskPlanItemService {
    @Resource
    private GovernCheckTaskPlanItemMapper governCheckTaskPlanItemMapper;
    @Resource
    private GovernHiddenInventoryService governHiddenInventoryService;
    @Resource
    private GovernCheckTaskItemService governCheckTaskItemService;
    @Resource
    private GovernCheckTaskPlanMapper governCheckTaskPlanMapper;
    @Resource
    private GovernCheckTaskInfoMapper governCheckTaskInfoMapper;
    @Resource
    private ISysUserService sysUserService;
    @Autowired
    private SysUserMapper userMapper;


    /**
     * 排查任务详情
     *
     * @param governTaskPlanItemId
     * @return
     */
    @Override
    public GovernCheckTaskPlanItemVo getTaskDetail(Long governTaskPlanItemId) {
        GovernCheckTaskPlanItem taskPlanItem = governCheckTaskPlanItemMapper.queryById(governTaskPlanItemId);
        GovernCheckTaskPlan taskPlan = governCheckTaskPlanMapper.queryById(taskPlanItem.getGovernTaskPlanId());

        GovernCheckTaskPlanItemVo taskPlanItemVo = new GovernCheckTaskPlanItemVo();
        BeanUtils.copyBeanProp(taskPlanItemVo, taskPlanItem);
        BeanUtils.copyBeanProp(taskPlanItemVo, taskPlan);

        return taskPlanItemVo;
    }

    /**
     * 查询检查详情
     *
     * @param governTaskPlanItemId
     * @return
     */
    @Override
    public GovernCheckTaskPlanItemVo selectTaskPlanItemDetail(Long governTaskPlanItemId) {
        GovernCheckTaskPlanItem taskPlanItem = governCheckTaskPlanItemMapper.queryById(governTaskPlanItemId);
        GovernCheckTaskPlan taskPlan = governCheckTaskPlanMapper.queryById(taskPlanItem.getGovernTaskPlanId());
        GovernCheckTaskInfo taskInfo = governCheckTaskInfoMapper.queryById(taskPlan.getGovernTaskInfoId());

        GovernCheckTaskPlanItemVo taskPlanItemVo = new GovernCheckTaskPlanItemVo();
        BeanUtils.copyBeanProp(taskPlanItemVo, taskPlanItem);
        taskPlanItemVo.setGovernCheckContent(taskPlanItem.getGovernCheckName() + " " + taskPlanItem.getGovernCheckContent());
        taskPlanItemVo.setTaskInfo(taskPlan, taskInfo);
        return taskPlanItemVo;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public GovernCheckTaskPlanItem queryById(Long id) {
        return this.governCheckTaskPlanItemMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param governCheckTaskPlanItem 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskPlanItem> queryByPage(GovernCheckTaskPlanItem governCheckTaskPlanItem) {
        governCheckTaskPlanItem.setGovernDeleted(0);
        governCheckTaskPlanItem.setIsGovernCheck(governCheckTaskPlanItem.getType());
        List<GovernCheckTaskPlanItem> list = this.governCheckTaskPlanItemMapper.queryAllByLimit(governCheckTaskPlanItem);
        if (StringUtils.isEmpty(list)) {
            return new ArrayList<GovernCheckTaskPlanItem>();
        }

        // 1，待定按钮不能点；2,待定|符合|不符合都不能点
        String submitStatus = null;
        GovernHiddenInventory inventory = null;
        for (GovernCheckTaskPlanItem item : list) {
            inventory = new GovernHiddenInventory();
            submitStatus = "0";

            // 0符合 1不符合 2待定
            // int confirm = item.getGovernCheckConform();
            inventory.setGovernDeleted(0);
            inventory.setGovernTaskPlanId(item.getGovernTaskPlanId());
            inventory.setGovernCheckTaskItemId(item.getGovernCheckTaskItemId());
            inventory = governHiddenInventoryService.queryByInventory(inventory);
            if (inventory!=null) {
                // 0 未上报  1已上报
                Integer inventoryConfirm = inventory.getGovernConfirm();
                submitStatus = inventoryConfirm == 1 ? "2" : "1";
            }

            GovernCheckTaskPlan plan = governCheckTaskPlanMapper.queryById(item.getGovernTaskPlanId());
            item.setGovernTaskStartTime(plan.getGovernTaskStartTime());
            item.setGovernTaskEndTime(plan.getGovernTaskEndTime());
            if (plan!=null) {
                // 0未上报  1已上报
                Integer planConfirm = plan.getGovernCheckVerify();
                submitStatus = planConfirm == 1 ? "2" : submitStatus;
            }

            item.setSubmitStatus(submitStatus);
        }

        return list;
    }


//    /**
//     * 查询排查任务
//     *
//     * @param governCheckTaskPlanItem 筛选条件
//     * @return 查询结果
//     */
//    @Override
//    public List<GovernCheckTaskPlanItem> queryTaskList(GovernCheckTaskPlanItem governCheckTaskPlanItem) {
//        List<GovernCheckTaskPlanItem> list = this.governCheckTaskPlanItemMapper.queryAllByLimit(governCheckTaskPlanItem);
//        if (StringUtils.isEmpty(list)) { return new ArrayList<GovernCheckTaskPlanItem>(); }
//
//        // 1，待定按钮不能点；2,待定|符合|不符合都不能点
//        String submitStatus = null;
//        GovernHiddenInventory inventory = null;
//        for (GovernCheckTaskPlanItem item : list) {
//            inventory = new GovernHiddenInventory();
//            submitStatus = "0";
//
//            // 0符合 1不符合 2待定
//            // int confirm = item.getGovernCheckConform();
//            inventory.setGovernDeleted(0);
//            inventory.setGovernTaskPlanId(item.getGovernTaskPlanId());
//            inventory.setGovernCheckTaskItemId(item.getGovernCheckTaskItemId());
//            inventory = governHiddenInventoryService.queryByInventory(inventory);
//            if (inventory!=null) {
//                // 0 未上报  1已上报
//                Integer inventoryConfirm = inventory.getGovernConfirm();
//                submitStatus = inventoryConfirm == 1 ? "2" : "1";
//            }
//
//            item.setSubmitStatus(submitStatus);
//        }
//
//        return list;
//    }


    /**
     * 查询
     *
     * @param governTaskPlanId 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskPlanItemVo> queryByTaskPlanId(Long governTaskPlanId) {
        List<GovernCheckTaskPlanItemVo> result = new ArrayList<GovernCheckTaskPlanItemVo>();
        GovernCheckTaskPlanItem governCheckTaskPlanItem = new GovernCheckTaskPlanItem();
        governCheckTaskPlanItem.setGovernTaskPlanId(governTaskPlanId);

        List<GovernCheckTaskPlanItem> list = this.queryByPage(governCheckTaskPlanItem);
        if (StringUtils.isEmpty(list)) {
            return result;
        }

        list.forEach(e -> result.add(new GovernCheckTaskPlanItemVo().pojoToVo(e)));
        return result;
    }

    public static void main(String[] args) {
//        String text = "企业选址及总平面布置安全（吴晓明）";
        String text = "设备管理（王思中、顾士家）";
        Pattern pattern = Pattern.compile("\\（(.*?)\\）");
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }

    public String importCheckUserHandler(String text) {
        text = text.replaceAll("（", "(");
        text = text.replaceAll("）", ")");
        Pattern pattern = Pattern.compile("\\((.*?)\\)");
        Matcher matcher = pattern.matcher(text);

        return matcher.find() ? matcher.group(1) : null;
    }

    /**
     * 分配检查人员
     *
     * @param list 检查人员
     * @return 查询结果
     */
    @Override
    public String allocateCheckUser2(List<GovernCheckTaskPlanItemVo> list, String loginUser) {
        if (CollectionUtils.isEmpty(list)) {
            return "导入数据不能为空！";
        }

        int i = 1;
        StringBuilder message = new StringBuilder();
        Map<String, List<GovernCheckTaskPlanItemVo>> collect = list.stream().collect(Collectors.groupingBy(GovernCheckTaskPlanItemVo::getGovernCheckUserName));
        Long[] itemIdsArray = new Long[0];
        String tempItemIds = null;
        String str = "导入失败的编号集：";
        message.append(str);
        for (Map.Entry<String, List<GovernCheckTaskPlanItemVo>> entry : collect.entrySet()) {
            String nickNames = entry.getKey();
            if (org.apache.commons.lang3.StringUtils.isEmpty(nickNames)) {
                continue;
            }
            List<GovernCheckTaskPlanItemVo> group = entry.getValue();
            List<Long> itemIds = group.stream()
                    .map(GovernCheckTaskPlanItemVo::getGovernTaskPlanItemId)
                    .collect(Collectors.toList());
            itemIdsArray = itemIds.toArray(new Long[0]);
            tempItemIds = String.join(",", Arrays.stream(itemIdsArray).map(String::valueOf).toArray(String[]::new));
            String[] userNameArray = null;
            StringBuilder userIds = new StringBuilder();
            StringBuilder usernames = new StringBuilder();
            try {
                nickNames = importCheckUserHandler(nickNames);

                if (nickNames.contains("、")) {
                    userNameArray = nickNames.split("、");
                } else {
                    userNameArray = new String[]{nickNames};
                }

                for (String uname : userNameArray) {
                    SysUser user = sysUserService.selectUserByNickName(uname);
                    if (user == null) {
                        message.append(tempItemIds).append("(检查人员名称未找到：").append(uname).append(")");
                        continue;
                    }
                    userIds.append(user.getUserId()).append(",");
                    usernames.append(user.getUserName()).append(",");
                }

                boolean b = governCheckTaskPlanItemMapper.updateUser(loginUser, nickNames, itemIds, userIds.substring(0, userIds.length() - 1));
                if (!b) {
                    message.append(tempItemIds);
                }
            } catch (Exception e) {
                message.append(tempItemIds);
                continue;
            }
        }
        if (str.equals(message.toString())) {
            message = new StringBuilder("导入成功！");
        }

        return message.toString();
    }

    public int updateTaskPlanCheckUser(GovernCheckTaskPlanItemVo itemVo, String loginUser, Set<String> userIds, Set<String> userNames) {
        if (itemVo==null || itemVo.getGovernTaskPlanItemId()==null ||
                StringUtils.isEmpty(userIds) || StringUtils.isEmpty(userNames)) {
            return -1;
        }

        Long taskPlanItemId = itemVo.getGovernTaskPlanItemId();
        GovernCheckTaskPlanItem planItem = this.queryById(taskPlanItemId);
        Long taskPlanId = planItem.getGovernTaskPlanId();

        GovernCheckTaskPlan entity = governCheckTaskPlanMapper.queryById(taskPlanId);
        String uIds = entity.getGovernCheckUserIds();
        String uNames = entity.getGovernCheckUserNames();
        if (StringUtils.isNotEmpty(uIds) && StringUtils.isNotEmpty(uNames)) {
            userIds.addAll(Arrays.asList(uIds.split(",")));
            userNames.addAll(Arrays.asList(uNames.split(",")));
        }

        GovernCheckTaskPlan taskPlan = new GovernCheckTaskPlan();
        taskPlan.setGovernTaskPlanId(taskPlanId);
        taskPlan.setGovernCheckUserIds(String.join(",", userIds));
        taskPlan.setGovernCheckUserNames(String.join(",", userNames));
        taskPlan.setGovernUpdateDate(new Date());
        taskPlan.setGovernUpdateBy(loginUser);

        governCheckTaskPlanMapper.update(taskPlan);
        return addUserRole(userIds);
    }

    /**
     * 人员添加角色
     * @param userIdList
     * @return
     */
    public int addUserRole(Set<String> userIdList) {
        if (StringUtils.isEmpty(userIdList)) {
            return -1;
        }

        for (String userId : userIdList) {
            SysUserRole userRole = sysUserService.selectByUserIdAndRoleId(Long.parseLong(userId), InspectionConstant.ROLE_ZXPC_ID);
            if (userRole==null) {
                sysUserService.insertUserAuth(Long.parseLong(userId), new Long[]{InspectionConstant.ROLE_ZXPC_ID});
            }
        }

        return 1;
    }

    /**
     * 分配检查人员
     *
     * @param list 检查人员
     * @return 查询结果
     */
    @Override
    public String allocateCheckUser(List<GovernCheckTaskPlanItemVo> list, String loginUser) {
        if (CollectionUtils.isEmpty(list)) {
            return "导入数据不能为空！";
        }
        Set<String> uIds = new HashSet<>();
        Set<String> uNames = new HashSet<>();

        StringBuilder message = new StringBuilder();
        Map<String, List<GovernCheckTaskPlanItemVo>> collect = list.stream().collect(Collectors.groupingBy(GovernCheckTaskPlanItemVo::getGovernCheckUserName));
        Long[] itemIdsArray = new Long[0];
        String tempItemIds = null;
        String str = "导入失败的编号集：";
        message.append(str);
        for (Map.Entry<String, List<GovernCheckTaskPlanItemVo>> entry : collect.entrySet()) {
            String nickNames = entry.getKey();
            if (org.apache.commons.lang3.StringUtils.isEmpty(nickNames)) {
                continue;
            }
            List<GovernCheckTaskPlanItemVo> group = entry.getValue();
            List<Long> itemIds = group.stream()
                    .map(GovernCheckTaskPlanItemVo::getGovernTaskPlanItemId)
                    .collect(Collectors.toList());
            itemIdsArray = itemIds.toArray(new Long[0]);
            tempItemIds = String.join(",", Arrays.stream(itemIdsArray).map(String::valueOf).toArray(String[]::new));
            String[] userNameArray = null;
            StringBuilder userIds = new StringBuilder();
            StringBuilder usernames = new StringBuilder();
            try {
                if (nickNames.contains(",") || nickNames.contains("，")) {
                    userNameArray = nickNames.replaceAll("，", ",").split(",");
                } else {
                    userNameArray = new String[]{nickNames};
                }

                for (String uname : userNameArray) {
                    SysUser user = sysUserService.selectUserByNickName(uname);
                    if (user == null) {
                        message.append(tempItemIds).append("(检查人员名称未找到：").append(uname).append(")");
                        continue;
                    }
                    uIds.add(user.getUserId()+"");
                    uNames.add(user.getNickName());

                    userIds.append(user.getUserId()).append(",");
                    usernames.append(user.getUserName()).append(",");
                }

                boolean b = governCheckTaskPlanItemMapper.updateUser(loginUser, nickNames, itemIds, userIds.substring(0, userIds.length() - 1));
                if (!b) {
                    message.append(tempItemIds);
                }
            } catch (Exception e) {
                message.append(tempItemIds);
                continue;
            }
        }

        updateTaskPlanCheckUser(list.get(0), loginUser, uIds, uNames);
        if (str.equals(message.toString())) {
            message = new StringBuilder("导入成功！");
        }

        return message.toString();
    }


    /**
     * 新增数据
     *
     * @param governCheckTaskPlanItem 实例对象
     * @return 实例对象
     */
    @Override
    public GovernCheckTaskPlanItem insert(GovernCheckTaskPlanItem governCheckTaskPlanItem) {
        governCheckTaskPlanItem.setGovernTaskPlanItemId(IdFactory.newLongId());
        governCheckTaskPlanItem.setGovernCreateDate(new Date());
        //governCheckTaskPlanItem.setGovernCreateBy(SecurityUtils.getUsername());
        governCheckTaskPlanItem.setGovernCreateBy("system");
        this.governCheckTaskPlanItemMapper.insert(governCheckTaskPlanItem);
        return governCheckTaskPlanItem;
    }

    /**
     * 新增数据
     *
     * @param governCheckTaskPlanItem 实例对象
     * @return 实例对象
     */
    @Override
    public int addCheckTaskPlanItems(GovernCheckTaskPlanItem governCheckTaskPlanItem, String userName) {
        Long[] itemIds = governCheckTaskPlanItem.getGovernTaskPlanItemIds();
        Long taskPlanId = governCheckTaskPlanItem.getGovernTaskPlanId();
        if (StringUtils.isEmpty(itemIds) || taskPlanId==null) {
            return 0;
        }

        Arrays.stream(itemIds).forEach(itemId -> {
            GovernCheckTaskPlanItem entity = new GovernCheckTaskPlanItem();
            entity.setGovernTaskPlanId(taskPlanId);
            entity.setGovernCheckTaskItemId(itemId+"");
            entity.setGovernDeleted(0);
            List<GovernCheckTaskPlanItem> list = governCheckTaskPlanItemMapper.queryAllByLimit(entity);
            if (StringUtils.isEmpty(list)) {
                GovernCheckTaskItem itemVo = governCheckTaskItemService.queryById(itemId);
                BeanUtils.copyProperties(itemVo, entity);
                entity.setGovernCheckTaskItemId(itemId+"");
                entity.setGovernTaskPlanItemId(IdFactory.newLongId());
                entity.setGovernCreateDate(new Date());
                entity.setGovernCreateBy(userName);
                entity.setGovernDeleted(0);
                entity.setGovernCheckResult("未排查");
                this.governCheckTaskPlanItemMapper.insert(entity);
            }
        });

        return 1;
    }


    /**
     * 修改数据
     * governTaskPlanItemId   计划任务子项ID
     * governCheckConform     0符合 1不符合 2待定中
     *
     * @param governCheckTaskPlanItem 实例对象
     * @return 实例对象
     */
    @Override
    public GovernCheckTaskPlanItem update(GovernCheckTaskPlanItem governCheckTaskPlanItem) {
        Integer comfirm = governCheckTaskPlanItem.getGovernCheckConform();
        if (comfirm != null && (comfirm.intValue() == 1 || comfirm.intValue() == 0)) {
            governCheckTaskPlanItem.setGovernCheckResult("已排查");
            governCheckTaskPlanItem.setGovernCheckTime(new Date());
        }
        governCheckTaskPlanItem.setGovernUpdateDate(new Date());
        this.governCheckTaskPlanItemMapper.update(governCheckTaskPlanItem);
        return this.queryById(governCheckTaskPlanItem.getGovernTaskPlanItemId());
    }

    /**
     * 重置所有任务项的检查人  BY 任务计划ID
     *
     * @param governTaskPlanId 任务计划ID
     * @return
     */
    @Override
    public int resetCheckUser(Long governTaskPlanId) {
        GovernCheckTaskPlanItem governCheckTaskPlanItem = new GovernCheckTaskPlanItem();
        governCheckTaskPlanItem.setGovernTaskPlanId(governTaskPlanId);
        governCheckTaskPlanItem.setGovernUpdateDate(new Date());
        //governCheckTaskPlanItem.setGovernCreateBy(SecurityUtils.getUsername());
        governCheckTaskPlanItem.setGovernUpdateBy("system");
        return this.governCheckTaskPlanItemMapper.resetCheckUser(governCheckTaskPlanItem);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.governCheckTaskPlanItemMapper.deleteById(id) > 0;
    }

    @Override
    public int deleteByGovernTaskPlanId(Long governTaskPlanId) {
        return this.governCheckTaskPlanItemMapper.deleteByGovernTaskPlanId(governTaskPlanId);
    }

}
